import 'package:built_collection/built_collection.dart';
import 'package:mobile_app.core/core/domain/entities/learning_content/collection_list_item/collection_list_item.dart';
import 'package:mobile_app.core/core/domain/entities/learning_content/lexical_item/lexical_item.dart';
import 'package:mobile_app.core/core/domain/entities/premium_access_status.dart';

abstract class GetPermittedLexicalItemIds {
  BuiltSet<String> call({
    required BuiltList<CollectionListItem> collectionListItems,
    required BuiltSet<String> permittedCollectionListItemIds,
    required BuiltMap<String, LexicalItem> lexicalItemMap,
    required PremiumAccessStatus premiumAccessStatus,
  });
}

class GetPermittedLexicalItemIdsImpl implements GetPermittedLexicalItemIds {
  const GetPermittedLexicalItemIdsImpl();

  @override
  BuiltSet<String> call({
    required BuiltList<CollectionListItem> collectionListItems,
    required BuiltSet<String> permittedCollectionListItemIds,
    required BuiltMap<String, LexicalItem> lexicalItemMap,
    required PremiumAccessStatus premiumAccessStatus,
  }) {
    if (premiumAccessStatus.hasFullAccess || premiumAccessStatus.isDemo) {
      return lexicalItemMap.keys.toBuiltSet();
    }

    final permittedLexicalItemIds = <String>{};

    for (final collectionListItem in collectionListItems) {
      if (permittedCollectionListItemIds.contains(collectionListItem.id)) {
        switch (collectionListItem) {
          case Collection():
            final collection = collectionListItem;
            permittedLexicalItemIds.addAll(collection.lexicalItemIds);

          case CollectionFolder():
            final collectionFolder = collectionListItem;

            for (final collection in collectionFolder.collections) {
              if (permittedCollectionListItemIds.contains(collection.id)) {
                permittedLexicalItemIds.addAll(collection.lexicalItemIds);
              }
            }
        }
      }
    }

    return permittedLexicalItemIds.build();
  }
}
